package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
)

/*
   Author: mahaiyuan
   Date: 2021/4/21 4:36 下午
   Description:
*/

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func main() {
	engine := gin.Default()
	engine.GET("/ping", func(ctx *gin.Context) {
		ctx.JSON(http.StatusOK, gin.H{"errno": 0})
	})
	engine.GET("/log", pushLog)
	engine.Run(":8888")
}

func pushLog(ctx *gin.Context) {
	//升级get请求为websocket协议
	ws, err := upgrader.Upgrade(ctx.Writer, ctx.Request, nil)
	if err != nil {
		fmt.Println("upgrade error.", err)
		return
	}
	defer ws.Close()

	for true {
		// 读取ws中的数据
		mt, message, err := ws.ReadMessage()
		if err != nil {
			fmt.Println("read message error.", err)
			break
		}
		if string(message) == "ping" {
			message = []byte("pong")
		}
		// 写入ws数据
		err = ws.WriteMessage(mt, message)
		if err != nil {
			fmt.Println("write message error.", err)
			break
		}
	}
}